package com.ahao.service;

import com.ahao.dao.UserDao;
import com.ahao.model.User;
import com.ahao.utils.CommonsUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class UserService {
    UserDao userDao = new UserDao();

    public Integer login(String username, String password, HttpServletRequest req) {
        try {
            //获取session对象
            HttpSession session = req.getSession();
            //获取存在session中的验证码
            String sessionVcode = (String) session.getAttribute("vcode");
            //获取用户输入的验证码
            String vcode = req.getParameter("vcode");
            if (vcode == null || !vcode.equalsIgnoreCase(sessionVcode)) {
                return CommonsUtils.BAD_VCODE;
            }
            User user =  userDao.selectUserByUsername(username);
            if (user == null) {
                return CommonsUtils.USERNAME_NOT_FIND_BAD_PASSWORD;
            }else {
                if(!user.getEnabled()){
                    return CommonsUtils.ACCOUNT_DISABLED;
                }else {
                    if (user.getPassword().equals(password)) {
                        //登录成功，将用户信息放入session
                        session.setAttribute("loginUser", user);
                        return CommonsUtils.LOGIN_SUCCESS;
                    }else {
                        return CommonsUtils.USERNAME_NOT_FIND_BAD_PASSWORD;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonsUtils.OTHER_EXCEPTION;
    }
}
